package com.wg.dome.attribute;

import com.wg.dome.entity.user.EquipEntity;
import com.wg.dome.entity.user.HeroEntity;
import com.wg.dome.repository.EquipRepository;
import com.wg.dome.repository.HeroRepository;

import java.io.Serializable;
import java.util.HashMap;

public class PlayerAttribute {
    private final long playerId;

    /**
     * 总属性
     * key 上阵位值 1-6.出战位置
     */
    private final HashMap<Byte, FightAttribute> attributes = new HashMap<>();

    public PlayerAttribute(long playerId) {
        this.playerId = playerId;
    }

    /**
     * 获取出战属性
     *
     * @param szPos      1-6 上阵位置
     * @param updateType 0.不更新 1.更新装备 2.更新英雄
     */
    public Attribute getFightAttribute(byte szPos, int updateType) {
        FightAttribute fightAttribute = attributes.computeIfAbsent(szPos, key -> {
            FightAttribute attribute = new FightAttribute();
            updateEquipAttribute(attribute, key);
            updateHeroAttribute(attribute, key);
            attribute.countTotalAttribute();
            return attribute;
        });

        if (updateType == 1) {
            updateEquipAttribute(fightAttribute, szPos);
            fightAttribute.countTotalAttribute();
        } else if (updateType == 2) {
            updateHeroAttribute(fightAttribute, szPos);
            fightAttribute.countTotalAttribute();
        }

        return fightAttribute.getTotalAttribute();
    }

    /**
     * 更新装备属性
     *
     * @param szPos 0.背包 1-6 上阵位置
     */
    private void updateEquipAttribute(FightAttribute fightAttribute, byte szPos) {
        EquipRepository equipRepository = new EquipRepository();
        HashMap<Serializable, EquipEntity> equipMap = equipRepository.getAll(playerId, entity -> entity.getPos() == szPos);

        fightAttribute.getEquipAttributs().clear();
        for (EquipEntity equipEntity : equipMap.values()) {
            fightAttribute.getEquipAttributs().add(AttributeHelper.countEquipAttribute(equipEntity));
        }
    }

    /**
     * 更新英雄属性
     *
     * @param szPos 0.背包 1-6 上阵位置
     */
    private void updateHeroAttribute(FightAttribute fightAttribute, byte szPos) {
        HeroRepository heroRepository = new HeroRepository();
        HeroEntity heroEntity = heroRepository.get(playerId, entity -> entity.getSzPos() == szPos);
        Attribute heroAttributes = heroEntity != null ? AttributeHelper.countHeroAttribute(heroEntity) : new Attribute();
        fightAttribute.setHeroAttribute(heroAttributes);
    }
}

